package openbang.chatroom.service.util;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import openbang.chatroom.service.vo.CacheKeyDefine;

/**
 * Cache工具
 * 
 * 基于GAE提供的 Cache服务
 * 
 * @author aibo zeng
 *
 */

public class CacheHelper {
	private static final Logger log = Logger.getLogger(CacheHelper.class.getName());
    private static Cache cache  = null ;
    private static OpenCacheListener openCacheListener = new OpenCacheListener();
    private synchronized  static Cache getCache(){
    	if(cache  == null){
	        try {
	            CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
	            cache = cacheFactory.createCache(Collections.emptyMap());
	            cache.put(CacheKeyDefine.SESSION_ALL, new HashSet<String>());
	            cache.put(CacheKeyDefine.CHATGROUP_ALL, new HashSet<String>());
	            //cache.addListener(openCacheListener);//好像不管用
	        } catch (CacheException e) {
	        	log.warning("init cache error");
	        }
    	}
    	return cache;
    }
	
    public static HashSet<String> getSessionAll(){
    	return (HashSet<String>)get(CacheKeyDefine.SESSION_ALL);
    }

    public static HashSet<String> getChatGroupAll(){
    	return (HashSet<String>)get(CacheKeyDefine.CHATGROUP_ALL);
    }
    public static Object get(String key){
    	//如果把最近访问日期注入？ CacheAvailable , 修改了，还得put, 影响性能
    	return getCache().get(key);
    }
    
    /**
     * 往Cache放入新的对象,并自动维护 All
     * @param key
     * @param obj
     */
    public static void add(String key , Object obj){
    	getCache().put(key,obj);
    	openCacheListener.onPut(key);
    }

    /**
     * 往Cache更新对象,不维护 All
     * @param key
     * @param obj
     */
    public static void put(String key , Object obj){
    	getCache().put(key,obj);
    }
    
    /**
     * 从Cache移除对象,并自动维护 All
     * @param key
     * @param obj
     */
    public static void remove(String key){    	
    	getCache().remove(key);
    	openCacheListener.onRmove(key);
    	
    	//GAE Cache不支持批量 remove ?
    }

    /**
     * 批量移除对象
     * 由于  remove()移除一个,维护一次All，为了增加效率，提供 removeAll
     * @param keySet
     * @param type  0 Session对象 , 1 chat group对象
     */
    public static void removeAll(Collection<String> keySet,int type){
    	for(String key : keySet){
    		getCache().remove(key);
    	}
    	if(type==0){
    		HashSet sAll = CacheHelper.getSessionAll();
    		sAll.removeAll(keySet);
    		CacheHelper.put(CacheKeyDefine.SESSION_ALL,sAll);
    	}
    	else if(type==1){
    		HashSet cAll = CacheHelper.getChatGroupAll();
    		cAll.removeAll(keySet);
    		CacheHelper.put(CacheKeyDefine.CHATGROUP_ALL,cAll);
    	}
    	else{    		
    	}
    }
    
}
